package com.brotherly.mpgp;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.util.BitmapUtil;

public class ArticleActivity extends BaseActivity implements OnClickListener {

    private class ContentAdapter extends PagerAdapter implements OnPageChangeListener {

        private ArrayList<View> mViews = null;

        public ContentAdapter(ArrayList<View> views)
        {
            this.mViews = views;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView(mViews.get(position));
        }

        @Override
        public int getCount()
        {
            return mViews.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            container.addView(mViews.get(position), lp);

            return mViews.get(position);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == arg1;
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {

        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {
            if (arg0 == ViewPager.SCROLL_STATE_IDLE || arg0 == ViewPager.SCROLL_STATE_SETTLING)
            {

            }
        }

        @Override
        public void onPageSelected(int arg0)
        {
            int index = mViewPager.getCurrentItem();

            if (index != -1)
            {
                try
                {
                    JSONObject article = mArticles.getJSONObject(arg0);
                    if (article.has("type") && article.getString("type").equals("course"))
                    {
                        mTitle.setText("攻略详情");
                    } else
                    {
                        mTitle.setText("活动详情");
                    }
                    int gameref = article.getInt("gameref");
                    JSONObject gamedata = mRelativeGames.get(gameref + "");
                    if (mIsShowRelatedGame)
                    {
                        View relativeGameContainer = ArticleActivity.this.mViews.get(index);
                        ImageView gameIcon = (ImageView) relativeGameContainer.findViewById(R.id.iv_relative_game);
                        TextView gameName = (TextView) relativeGameContainer.findViewById(R.id.tv_relative_game);
                        if (gamedata != null)
                        {
                            gameName.setText(gamedata.getString("name"));
                            updateGameIcon(gameref, gameIcon, relativeGameContainer);
                        } else
                        {
                            downLoadGameInfo(gameref);
                        }
                    }
                    updateFavorateBtn();
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private JSONArray mArticles;
    private int TAG_RELATIVE = 0;
    // private ImageView mGameIcon;
    // private TextView mGameName;
    private View mLeftArrowBtn = null;
    private View mRightArrowBtn = null;
    private int mStartIndex = 0;
    private TextView mTitle;
    private ViewPager mViewPager = null;
    private ArrayList<View> mViews = null;
    private Button mFavorite;
    private Button mShare;
    /*
     * key - id value - iconurl
     */
    private HashMap<String, JSONObject> mRelativeGames;
    private boolean mIsShowRelatedGame = true;

    // private LinearLayout mRelativeGame;

    private int converToPx(int dp)
    {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    private View createArticleDetailItemView(JSONObject article)
    {

        LayoutInflater mInflater = LayoutInflater.from(this);

        View relativeView = mInflater.inflate(R.layout.relative_game_item, null);

        View item = mInflater.inflate(R.layout.article_detail_item, null);

        LinearLayout container = (LinearLayout) item.findViewById(R.id.article_detial_container);

        int padding = converToPx(25);

        try
        {
            JSONArray contents = new JSONArray(article.getString("content"));
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("title".equals(type))
                {
                    TextView title = new TextView(this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                    title.setGravity(Gravity.CENTER);
                    title.setPadding(padding << 1, padding >> 2, padding << 1, padding >> 2);
                    title.setText(content.getString("content"));
                    title.setTextColor(0xFF000000);
                    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                    container.addView(title, lp);
                    item.setTag(content.getString("content"));
                    article.put("title", content.getString("content"));
                    continue;
                }
                if ("tip".equals(type))
                {
                    TextView tip = new TextView(this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                    tip.setGravity(Gravity.CENTER);
                    tip.setPadding(padding, 0, padding, padding >> 1);
                    tip.setText(content.getString("content"));
                    tip.setTextColor(0xFF717276);
                    tip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    container.addView(tip, lp);
                    continue;
                }
                if ("para".equals(type))
                {
                    TextView para = new TextView(this);
                    para.setPadding(padding, padding >> 2, padding, padding >> 2);
                    para.setText(content.getString("content"));
                    para.setTextColor(0xFF717276);
                    para.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    container.addView(para);
                    continue;
                }
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    JSONObject io = article.getJSONObject("info");
                    if (!io.has(key))
                    {
                        continue;
                    }
                    JSONArray ia = io.getJSONArray(key);
                    if (ia.length() == 0)
                    {
                        continue;
                    }
                    int id = ia.getJSONObject(0).getInt("id");
                    LinearLayout.LayoutParams lp = null;
                    ImageView img = new ImageView(this);
                    img.setScaleType(ScaleType.CENTER_CROP);
                    img.setPadding(0, 0, 0, 0);
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/blob?ref=")
                            .append(id).toString();
                    String cachePath = internetResourceDownload(imageurl);
                    if (cachePath != null)
                    {
                        Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
                        // Bitmap bitmap = BitmapFactory.decodeFile(cachePath);
                        if (bitmap == null)
                        {
                            lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            // removeCachedData(imageurl);
                            // internetResourceDownload(imageurl);
                        } else
                        {
                            int iw = converToPx(305);
                            float gene = bitmap.getWidth() / (bitmap.getHeight() + 0f);
                            int ih = (int) (iw / gene);
                            lp = new LinearLayout.LayoutParams(iw,
                                    ih);
                            img.setImageBitmap(bitmap);
                        }
                    } else
                    {
                        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
                    }

                    img.setTag(imageurl);
                    container.addView(img, lp);
                    continue;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        if (mIsShowRelatedGame)
        {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    converToPx(128));
            container.addView(relativeView, lp);
            relativeView.setTag(TAG_RELATIVE);
            relativeView.setOnClickListener(this);
        }
        return item;
    }

    private void downLoadGameInfo(int gameRef)
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameDetail(gameRef);
    }

    private void initViewPager(JSONArray items)
    {
        mViewPager = (ViewPager) findViewById(R.id.sv_article_content);
        mViews.clear();
        for (int i = 0; i < items.length(); i++)
        {
            try
            {
                JSONObject j = items.getJSONObject(i);
                View v = createArticleDetailItemView(j);
                mViews.add(v);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        ContentAdapter adapter = new ContentAdapter(mViews);
        mViewPager.setAdapter(adapter);
        mViewPager.setOnPageChangeListener(adapter);
    }

    private void nextPage()
    {
        int currentItem = mViewPager.getCurrentItem();
        int count = mViewPager.getAdapter().getCount();
        if (currentItem >= count)
        {
            return;
        }
        mViewPager.setCurrentItem(currentItem + 1, true);
    }

    @Override
    public void onAllReady()
    {
        if (mArticles != null)
        {
            ((ContentAdapter) mViewPager.getAdapter()).onPageSelected(mViewPager.getCurrentItem());
            return;
        }
        mStartIndex = getIntent().getIntExtra("Index", 0);
        mTitle = (TextView) findViewById(R.id.tv_title);
        // mGameIcon = (ImageView) findViewById(R.id.iv_relative_game);
        // mGameName = (TextView) findViewById(R.id.tv_relative_game);
        mViews = new ArrayList<View>();
        // mRelativeGame = (LinearLayout) findViewById(R.id.ll_relative_game);
        // mRelativeGame.setOnClickListener(this);
        mFavorite = (Button) findViewById(R.id.btn_add_favorite);
        mFavorite.setOnClickListener(this);
        mShare = (Button) findViewById(R.id.btn_share);
        mShare.setOnClickListener(this);
        try
        {
            String articles = getIntent().getStringExtra("Articles");
            mArticles = new JSONArray(articles);
            initViewPager(mArticles);
            mViewPager.setCurrentItem(mStartIndex);
            ((ContentAdapter) mViewPager.getAdapter()).onPageSelected(0);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        mLeftArrowBtn = findViewById(R.id.btn_left_arrow);
        mRightArrowBtn = findViewById(R.id.btn_right_arrow);

        mLeftArrowBtn.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                prePage();
            }
        });

        mRightArrowBtn.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                nextPage();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);

        mIsShowRelatedGame = getIntent().getBooleanExtra("isShowRelatedGame", false);
        mRelativeGames = new HashMap<String, JSONObject>();
    }

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (RemoteServerService.RemoteServer_Event_RemoteServer_Success.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_DETAIL.equals(param1))
            {
                final JSONObject data = (JSONObject) param2;
                try
                {
                    final int gameid = data.getInt("id");
                    mRelativeGames.put(gameid + "", data);
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            ((ContentAdapter) mViewPager.getAdapter()).onPageSelected(mViewPager.getCurrentItem());
                        }
                    });

                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        } else if (RemoteServerService.RemoteServer_Event_RemoteServer_Error.equals(id))
        {

        }
        else if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            updateArticleImage((String) param1);
            runOnUiThread(new Runnable()
            {

                @Override
                public void run()
                {
                    ((ContentAdapter) mViewPager.getAdapter()).onPageSelected(mViewPager.getCurrentItem());
                }
            });
        }
    }

    private void prePage()
    {
        int currentItem = mViewPager.getCurrentItem();
        if (currentItem > 0)
        {
            mViewPager.setCurrentItem(currentItem - 1, true);
        }
    }

    private synchronized void updateArticleImage(String url)
    {
        for (View v : new ArrayList<View>(mViews))
        {
            final ImageView img = (ImageView) v.findViewWithTag(url);
            if (img == null)
            {
                continue;
            }
            String cachePath = internetResourceDownload(url);
            if (cachePath != null)
            {
                final Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
                // final Bitmap bitmap = BitmapFactory.decodeFile(cachePath);
                if (bitmap != null)
                {
                    runOnUiThread(new Runnable()
                    {

                        @Override
                        public void run()
                        {
                            int iw = converToPx(305);
                            float gene = bitmap.getWidth() / (bitmap.getHeight() + 0f);
                            int ih = (int) (iw / gene);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(iw,
                                    ih);
                            img.setImageBitmap(bitmap);
                            img.setLayoutParams(lp);
                        }
                    });
                }
            }
        }
    }

    /**
     * @param gameid
     */
    private void updateGameIcon(int gameid, ImageView gameIcon, View relativeGameContainer)
    {
        try
        {
            String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                    .append("games/blob?key=image&gameref=")
                    .append(gameid).toString();
            if (imageurl == null)
                return;
            gameIcon.setTag(imageurl);
            if (imageViewLoadInternetResource(gameIcon, imageurl, R.drawable.grap_icon))
            {
                relativeGameContainer.findViewById(R.id.ll_recommend_game).setVisibility(View.VISIBLE);
                LayoutParams lp = (LayoutParams) gameIcon.getLayoutParams();
                lp.width = converToPx(75);
                lp.height = converToPx(75);
                gameIcon.setLayoutParams(lp);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v)
    {
        if (v.getTag() != null && v.getTag() instanceof Integer && 0 == (Integer) v.getTag())
        {
            if (mViewPager.getCurrentItem() == -1)
            {
                return;
            }
            try
            {
                JSONObject item = mArticles.getJSONObject(mViewPager.getCurrentItem());
                if (item.has("gameref") && item.has("identifier"))
                {
                    Intent intent = new Intent(ArticleActivity.this, GameDetailActivity.class);
                    int gameref = item.getInt("gameref");
                    intent.putExtra("gameref", gameref);
                    intent.putExtra("packageName", item.getString("identifier"));
                    startActivity(intent);
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        } else if (v == mFavorite)
        {
            if (mViewPager.getCurrentItem() == -1)
            {
                return;
            }
            try
            {
                String msg = "";
                JSONObject item = mArticles.getJSONObject(mViewPager.getCurrentItem());
                boolean hasFav = isFavoriteArticle(item.getInt("id"));
                if (hasFav)
                {
                    delFavoriteArticle(item.getInt("id"));
                    msg = "取消收藏成功！";
                } else
                {
                    favoriteArticle(item.getInt("id"), item);
                    msg = "收藏成功！";
                }
                Toast.makeText(ArticleActivity.this, msg, Toast.LENGTH_SHORT).show();
                updateFavorateBtn();
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }

        } else if (v == mShare)
        {
            if (mViewPager.getCurrentItem() == -1)
            {
                return;
            }
            try
            {
                JSONObject item = mArticles.getJSONObject(mViewPager.getCurrentItem());
                if (item.has("id"))
                {
                    if (item.has("title"))
                    {
                        shareArticle(item.getString("title"), item.getInt("id"));
                    } else
                    {
                        shareArticle(null, item.getInt("id"));
                    }
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }

    private void updateFavorateBtn()
    {
        try
        {
            JSONObject item = mArticles.getJSONObject(mViewPager.getCurrentItem());
            boolean hasFav = isFavoriteArticle(item.getInt("id"));
            if (hasFav)
            {
                mFavorite.setBackgroundResource(R.drawable.game_detail_favorite_pressed);
            } else
            {
                mFavorite.setBackgroundResource(R.drawable.game_detail_favorite);
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
    }

}
